package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.BaseTreeUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.CategoryVo;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.atguigu.gulimall.product.constant.ProductConstant.*;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryVo> listWithTreeVo() {
        // 1、查出表中所有商品分类信息
        List<CategoryEntity> categories = baseMapper.selectList(null);
        // 封装商品分类信息
        List<CategoryVo> collect = categories.stream().map(CategoryVo::new).collect(Collectors.toList());
        List<CategoryVo> treeNodes = BaseTreeUtils.listTreeNodes(collect);
        return treeNodes;
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查出表中所有商品分类信息
        List<CategoryEntity> categories = baseMapper.selectList(null);
        // 2、将所有分类信息组装成树形结构
        // 2.1、找到所有一级分类
        List<CategoryEntity> level1Menus = categories.stream().filter(categoryEntity ->
                        categoryEntity.getParentCid() == 0
                // 2.2、找到当前分类下的商品子菜单
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, categories));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO:检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        paths.add(catelogId);
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            paths.add(categoryEntity.getParentCid());
            CategoryEntity category = baseMapper.selectById(categoryEntity.getParentCid());
            if (category.getParentCid() != 0) {
                paths.add(category.getParentCid());
            }
        }
        Collections.reverse(paths);
        Long[] catelogPath = new Long[paths.size()];
        paths.toArray(catelogPath);
        return catelogPath;
    }

    @Override
    @Transactional  // 开启事务
    @CacheEvict(value = {"category"}, key = "'level1Categorys'")
    public void updateCascade(CategoryEntity category) {
        // 保证其他表中冗余字段的数据一致
        this.updateById(category);
        if (StringUtils.hasText(category.getName())) {
            // 同步更新其他关联表中的数据
            categoryBrandRelationService.updateCatelogName(category.getCatId(), category.getName());
        }
    }

    @Override
    @Cacheable(value = {"category"}, key = "'level1Categorys'", sync = true)
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = this.list(new QueryWrapper<CategoryEntity>().eq("cat_level", CAT_LEVEL_ONE));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String catalogJson = ops.get(LEVEL_TWO_AND_THREE_JSON);
        Map<String, List<Catelog2Vo>> catelog2VoMap = null;
        if (StringUtils.isEmpty(catalogJson)) {
            // 缓存不命中，加锁。查询数据库，获取数据
            RLock lock = redisson.getLock(CATALOG_JSON_REDIS_LOCK);
            lock.lock(CACHE_CATALOG_LOCK_TTL, TimeUnit.SECONDS);
            try {
                if (StringUtils.isEmpty(ops.get(LEVEL_TWO_AND_THREE_JSON))) {
                    List<CategoryEntity> categoryList = baseMapper.selectList(null);
                    catelog2VoMap = this.getCatalog2VoMap(categoryList);
                    String catalogJsonMap = JSON.toJSONString(catelog2VoMap);
                    ops.set(LEVEL_TWO_AND_THREE_JSON, catalogJsonMap, CACHE_CATALOG_JSON_TTL, TimeUnit.MINUTES);
                    return catelog2VoMap;
                }
            } finally {
                lock.unlock();
            }
        }
        // 若缓存中有json数据，则将获取到的json数据转换成前端需要的map对象
        catelog2VoMap = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return catelog2VoMap;
    }

    /**
     * 递归获取当前商品的子类菜单
     *
     * @param root 当前商品
     * @param all  所有菜单信息
     * @return 当前商品的子类菜单
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId()
        ).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    /**
     * 根据父id获取指定的商品分类集合
     *
     * @param categoryList
     * @param parentId
     * @return
     */
    private List<CategoryEntity> getCatalogByParentId(List<CategoryEntity> categoryList, Long parentId) {
        List<CategoryEntity> collect = categoryList.stream().filter(item -> item.getParentCid() == parentId)
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * 从商品分类集合中筛选出子分类，并封装成map
     *
     * @param categoryList
     * @return
     */
    private Map<String, List<Catelog2Vo>> getCatalog2VoMap(List<CategoryEntity> categoryList) {
        List<CategoryEntity> level1Categorys = getCatalogByParentId(categoryList, 0L);
        Map<String, List<Catelog2Vo>> catelog2VoMap = level1Categorys.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(), v -> {
                    // 每一个一级分类，查到对应的二级分类
                    List<CategoryEntity> childCategoryList = getCatalogByParentId(categoryList, v.getCatId());
                    List<Catelog2Vo> catelog2VoList = null;
                    if (!CollectionUtils.isEmpty(childCategoryList)) {
                        catelog2VoList = childCategoryList.stream().map(item -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(),
                                    null, item.getCatId().toString(), item.getName());
                            // 找当前二级分类的三级分类，封装成vo
                            List<CategoryEntity> catelog3List = getCatalogByParentId(categoryList, item.getCatId());
                            if (!CollectionUtils.isEmpty(catelog3List)) {
                                List<Catelog2Vo.Catelog3Vo> catelog3VoList = catelog3List.stream().map(l3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item.getCatId().toString(),
                                            l3.getCatId().toString(), l3.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(catelog3VoList);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catelog2VoList;
                }));
        return catelog2VoMap;
    }
}